package com.sailfish.springbootdemo.service.db1;


import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TechDeviceParamTypeServiceImpl implements TechDeviceParamTypeService {

    @Autowired
    private TechDeviceParamTypeDao techDeviceParamTypeDao;

    @Autowired
    private TechDeviceParamDao techDeviceParamDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private PcbaDeviceParamDao pcbaDeviceParamDao;

    @Autowired
    private PcbaDeviceParamTypeDao pcbaDeviceParamTypeDao;

    @Autowired
    private CommonJudgeCanDeleteService commonService;

    @Autowired
    private OperateService operateService;

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;
    @Value("${personal.config.env}")
    private String env;


    private String operateSmallType = "工艺大类";

    @Override
    public List<TechDeviceParamType> getTechDeviceParamTypeByPcbaDeviceTypeId(HttpServletRequest request, Integer pcbaDeviceTypeId, String searchValue) {
        List<TechDeviceParamType> list = techDeviceParamTypeDao.getAllTechDeviceParamTypeByDeviceType(pcbaDeviceTypeId, searchValue);
        for (TechDeviceParamType techDeviceParamType : list) {
            List<TechDeviceParam> byPcbaDeviceParamTypeId = techDeviceParamDao.getByTechDeviceParamTypeId(techDeviceParamType.getTechDeviceParamTypeId());

            for (TechDeviceParam techDeviceParam : byPcbaDeviceParamTypeId) {
                List<PcbaDeviceParam> pl = new ArrayList<>();
                if (techDeviceParam.getBindDeviceParamKey() != null && !"".equals(techDeviceParam.getBindDeviceParamKey())) {
                    String[] arr = techDeviceParam.getBindDeviceParamKey().split(",");
                    for (String s : arr) {
                        PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(s);
                        if (pcbaDeviceParamByKey != null) {
                            pcbaDeviceParamByKey.setPcbaDeviceParamType(pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeById(pcbaDeviceParamByKey.getPcbaDeviceParamTypeId()));
                            pl.add(pcbaDeviceParamByKey);
                        }
                    }
                }
                techDeviceParam.setBindDeviceParamList(pl);

                if (env != null && env.contains("pro"))  {
                    techDeviceParam.setTechDeviceParamPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + techDeviceParam.getTechDeviceParamPicture()));
                } else {
                    if(request != null){
                        techDeviceParam.setTechDeviceParamPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(CommonUtils.getApiPrefixUrl(request) + "/" + techDeviceParam.getTechDeviceParamPicture()));
                    }
                }

            }

            techDeviceParamType.setTechDeviceParamList(byPcbaDeviceParamTypeId);

            PcbaDeviceType byId = pcbaDeviceTypeDao.getById(techDeviceParamType.getPcbaDeviceTypeId());
            techDeviceParamType.setPcbaDeviceType(byId);
        }
        return list;
    }

    @Override
    public Result deleteTechDeviceParamType(Integer techDeviceParamTypeId) {
        try {
            if (techDeviceParamTypeId == null || "".equals(techDeviceParamTypeId.toString())) {
                return ResultUtil.error(500, "缺少参数techDeviceParamTypeId", "Miss Param techDeviceParamTypeId", null);
            }
            Map<String, Integer> stringIntegerMap = commonService.judgeCanDeleteTechDeviceParamType(techDeviceParamTypeId);
            if (stringIntegerMap.get("techDeviceParamNum") > 0) {
                return ResultUtil.error(500,
                        "禁止删除，当前项" + stringIntegerMap.get("techDeviceParamNum") + "处关联工艺模板",
                        "Forbidden Delete", null);
            }

            String userId = UserHeaderHolder.getUserId();
            TechDeviceParamType oldTechDeviceParamType = techDeviceParamTypeDao.getPcbaDeviceParamTypeById(techDeviceParamTypeId);

            Integer integer = techDeviceParamTypeDao.deleteTechDeviceParamType(techDeviceParamTypeId);
            if (integer > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(oldTechDeviceParamType), null));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result addOrUpdateTechDeviceParamType(String mode, TechDeviceParamType techDeviceParamType) {
        try {
            if (techDeviceParamType == null) {
                return ResultUtil.error(500, "缺少参数techDeviceParamType", "Miss Param techDeviceParamType", null);
            }
            if (mode == null || "".equals(mode)) {
                return ResultUtil.error(500, "缺少参数mode", "Miss Param mode", null);
            }
            if (!("edit".equals(mode) || "add".equals(mode))) {
                return ResultUtil.error(500, "mode 参数错误", "mode Param Error", null);
            }

            String userId = UserHeaderHolder.getUserId();

            if ("edit".equals(mode)) {
                if (techDeviceParamType.getTechDeviceParamTypeId() == null || "".equals(techDeviceParamType.getTechDeviceParamTypeId().toString())) {
                    return ResultUtil.error(500, "缺少参数techDeviceParamTypeId", "Miss Param techDeviceParamTypeId", null);
                }

                TechDeviceParamType oldTechDeviceParamType = techDeviceParamTypeDao.getPcbaDeviceParamTypeById(techDeviceParamType.getTechDeviceParamTypeId());

                List<TechDeviceParamType> techDeviceParamTypeList = techDeviceParamTypeDao.judgeUniqueTechDeviceParamType(techDeviceParamType.getTechDeviceParamTypeId(), techDeviceParamType.getPcbaDeviceTypeId(), techDeviceParamType.getTechDeviceParamTypeName());
                if (techDeviceParamTypeList.size() > 0) {
                    return ResultUtil.error(500, "修改失败，存在相同名字", "Operate Fail", null);
                }

                Integer integer = techDeviceParamTypeDao.updateTechDeviceParamType(techDeviceParamType);
                if (integer > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldTechDeviceParamType), JSONObject.toJSONString(techDeviceParamType)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            } else {

                TechDeviceParamType byTechDeviceTypeIdAndName = techDeviceParamTypeDao.getByTechDeviceTypeIdAndName(techDeviceParamType.getPcbaDeviceTypeId(), techDeviceParamType.getTechDeviceParamTypeName());
                if (byTechDeviceTypeIdAndName != null) {
                    return ResultUtil.error(500, "该类型已存在", "Already Exist", null);
                }

                techDeviceParamType.setCreateTime(new Date());
                Integer integer = techDeviceParamTypeDao.addTechDeviceParamType(techDeviceParamType);
                if (integer > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(techDeviceParamType)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
